<template>
  <div class="inventory">
    <el-dialog
      width="990px"
      title="选择库存"
      :visible.sync="showDialogVisible"
      :before-close="beforeClose"
      custom-class="revenue-code-number"
    >
      <div class="el-dialog__body-bodys">
        <div v-if="mode !== 'radio'" class="container">
          <div class="header">已选择({{ inventoryTableData2.length }}个)</div>
          <div class="ccui-multifunctional-table-wrapper">
            <el-table
              :data="inventoryTableData2"
              ref="multipleTable2"
              height="200"
              border
              :fit="true"
              row-key="pkPurmatdetl"
            >
              <el-table-column label="序号" width="45" fixed>
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column
                v-for="(table, index) in tableHeadOptions"
                :fixed="table.fixed || false"
                :key="index"
                :type="table.type"
                :label="table.label"
                :min-width="table.width"
                :prop="table.prop"
                :align="table.align || 'left'"
                :header-align="table.headerAlign || 'left'"
                :filters="table.filters"
                :formatter="table.formatter"
                :show-overflow-tooltip="true"
              />
              <el-table-column label="操作" width="50px" fixed="right">
                <template slot-scope="{ row, $index }">
                  <el-button
                    size="mini"
                    type="text"
                    @click="inventoryDeleteTable(row, $index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <div v-else class="alert-box">
          <el-alert
            :title="alertParams.title"
            :type="alertParams.type"
            :closable="false"
          />
        </div>

        <div class="container">
          <!-- 搜索条件开始 -->
          <el-search
            ref="search"
            :formProp="inventoryForm"
            @search="inventorySearch"
            @change="inventoryChange"
            width="400px"
            placement="bottom-start"
            class="ccui-highsearch no-print"
          >
            <template slot="search">
              <template v-for="(item, index) in searchInputArr">
                <!-- 时间区间 -->
                <el-date-picker
                  v-if="item.type === 'daterange'"
                  :key="index"
                  v-model="inventoryForm[item.value]"
                  value-format="yyyy-MM-dd"
                  :searchLabel="item.label"
                  :clearable="false"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
                <!-- 单个时间 -->
                <el-date-picker
                  v-else-if="item.type === 'date'"
                  :key="index"
                  v-model="inventoryForm[item.value]"
                  value-format="yyyy-MM-dd"
                  :searchLabel="item.label"
                  :clearable="false"
                  type="date"
                  placeholder="选择日期"
                />
                <!-- 下拉框 -->
                <el-select
                  v-else-if="item.type === 'select'"
                  :key="index"
                  v-model="inventoryForm[item.value]"
                  :searchLabel="item.label"
                  :placeholder="`请选择${item.label}`"
                >
                  <el-option
                    v-for="item in item.selectData"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
                <!-- 单选按钮 -->
                <el-radio-group
                  v-else-if="item.type === 'radio'"
                  v-model="inventoryForm[item.value]"
                  :key="index"
                  :searchLabel="item.label"
                  :placeholder="`请选择${item.label}`"
                >
                  <el-radio
                    v-for="n in item.radioData"
                    :key="n.value"
                    :label="n.value"
                    >{{ n.label }}</el-radio
                  >
                </el-radio-group>
                <!-- 输入框 -->
                <el-input
                  v-else
                  :key="index"
                  v-model.trim="inventoryForm[item.value]"
                  clearable
                  :searchLabel="item.label"
                  :placeholder="`请输入${item.label}模糊查询`"
                />
              </template>
            </template>
            <template v-for="(item, index) in searchInputArr">
              <!-- 时间区间 -->
              <el-date-picker
                v-if="item.type === 'daterange'"
                :key="index"
                v-model="inventoryForm[item.value]"
                value-format="yyyy-MM-dd"
                :searchLabel="item.label"
                :clearable="false"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :slot="`searchItem${index + 1}`"
              />
              <!-- 单个时间 -->
              <el-date-picker
                v-else-if="item.type === 'date'"
                :key="index"
                v-model="inventoryForm[item.value]"
                value-format="yyyy-MM-dd"
                :searchLabel="item.label"
                :clearable="false"
                type="date"
                placeholder="选择日期"
                :slot="`searchItem${index + 1}`"
              />
              <!-- 下拉框 -->
              <el-select
                v-else-if="item.type === 'select'"
                :key="index"
                v-model="inventoryForm[item.value]"
                :searchLabel="item.label"
                :placeholder="`请选择${item.label}`"
                :slot="`searchItem${index + 1}`"
              >
                <el-option
                  v-for="item in item.selectData"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <!-- 单选按钮 -->
              <el-radio-group
                v-else-if="item.type === 'radio'"
                v-model="inventoryForm[item.value]"
                :key="index"
                :searchLabel="item.label"
                :slot="`searchItem${index + 1}`"
              >
                <el-radio
                  v-for="n in item.radioData"
                  :key="n.value"
                  :label="n.value"
                  >{{ n.label }}</el-radio
                >
              </el-radio-group>
              <!-- 输入框 -->
              <el-input
                v-else
                :key="index"
                v-model.trim="inventoryForm[item.value]"
                clearable
                :searchLabel="item.label"
                :placeholder="`请输入${item.label}模糊查询`"
                :slot="`searchItem${index + 1}`"
              />
            </template>
          </el-search>
          <!-- 搜索条件结束 -->
          <div class="ccui-multifunctional-table-wrapper">
            <el-table
              :data="inventoryTableDatas"
              height="200"
              @selection-change="handleSelectionChange"
              @row-click="rowClick"
              ref="inventoryMultipleTable"
              border
              :fit="true"
              row-key="pkPurmatdetl"
            >
              <el-table-column
                v-if="mode === 'checkbox'"
                width="35"
                type="selection"
                reserve-selection
              />

              <el-table-column label="序号" width="45" align="center" fixed>
                <template slot-scope="{ $index }">
                  <span>{{ $index + 1 }}</span>
                </template>
              </el-table-column>

              <el-table-column
                v-for="(table, index) in tableHeadOptions"
                :fixed="table.fixed || false"
                :key="index"
                :type="table.type"
                :label="table.label"
                :min-width="table.width"
                :prop="table.prop"
                :align="table.align || 'left'"
                :header-align="table.headerAlign || 'left'"
                :filters="table.filters"
                :formatter="table.formatter"
                :show-overflow-tooltip="true"
              />

              <!-- <el-table-column
                label="操作"
                width="70"
                align="center"
                fixed="right"
              >
                <template slot-scope="{ row }">
                  <el-button type="text" @click="selectRow(row)"
                    >选择</el-button
                  >
                </template>
              </el-table-column> -->
            </el-table>
          </div>
          <div class="table-footer" style="height: 30px">
            <div class="ccui-table-footer">
              <div id="ccui-paging">
                <el-pagination
                  :total="inventoryTotal"
                  :page-size="inventoryPageSize"
                  :current-page="inventoryPageNoCode"
                  prev-text="< 上一页"
                  next-text="下一页 >"
                  background
                  layout="total, prev, pager, next, jumper"
                  popper-class="ccui-paging-page-size-popper"
                  @current-change="inventoryHandleCurrentChange"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-if="mode !== 'radio'" slot="footer" class="dialog-footer">
        <el-button size="mini" type="default-mini" @click="beforeClose"
          >取 消</el-button
        >
        <el-button
          size="mini"
          type="primary-font-mini"
          @click="inventoryConfirm"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from "lodash";
import { loadingParams } from "@/basa/utils/public";
import { generateUUID,formatNumber } from "@/basa/utils";
import flexColumnWidth from "@/basa/mixins/flexColumnWidth";
import {listSmpStockForInventoryPage} from '../api'
export default {
  name: "dialogMultiSelectTable",
  mixins: [flexColumnWidth],
  props: {
    // 错误提示
    errorMessage: {
      type: String,
      default: ""
    },
    // 搜索条件
    searchInputArr: {
      type: Array,
      default: () => []
    },
    // 表格的表头
    tableHeadOptions: {
      type: Array,
      default: () => []
    },
    // 通过页面传进来的方法获取数据
    getTableList: {
      type: Function,
      default: Function
    },
    // 可选择的参数
    optionalParams: {
      type: Object,
      default: () => {}
    },
    // 回显已选中的数据
    selectTableList: {
      type: Array,
      default: () => []
    },
    // 条件判断显示
    isShow: {
      type: Boolean,
      default: false
    },
    // alert 弹框参数
    alertParams: {
      type: Object,
      default: () => ({
        title: "警告信息",
        type: "error"
      })
    },
    // 是否默认展开搜索条件
    isOpenSearch: {
      type: Boolean,
      default: false
    },
    // 使用什么状态选择
    mode: {
      validator: value => {
        return ["checkbox", "radio"].includes(value);
      },
      default: "checkbox"
    },
    warehouseId:{
        type:Number
    }
  },
  data() {
    return {
      showDialogVisible: false,
      inventoryForm: {},
      inventoryTableDatas: [],//初始表格
      inventoryTotal: 0,
      inventoryPageNoCode: 1,
      inventoryPageSize: 10,
      inventoryTableData2: [] //所有选中的数据包含跨分页数据
    };
  },
  methods: {
    showDialog() {
      if (this.isShow) {
        this.showDialogVisible = true;
        this.$nextTick(() => {
          // 是否默认展开搜索条件
          this.$refs.search.isShowBottom = this.isOpenSearch;
          // radio 类型的搜索条件，默认第一个选中
          // const radioObj = this.searchInputArr.find(_ => _.type === "radio");
          // if (radioObj) {
          //   this.inventoryForm[radioObj.value] = radioObj.radioData[0].value;
          // }
        });
        this.inventoryGetMcConcBill();
      } else {
        this.$showErrorMessage(this.errorMessage);
      }
    },
    inventoryGetMcConcBill() {
      // 过滤时间参数
      const tempForm = cloneDeep(this.inventoryForm);
      for (const key in tempForm) {
        if (Object.hasOwnProperty.call(tempForm, key)) {
          const ele = tempForm[key];
          const { type } = this.searchInputArr.find(_ => _.value === key);
          switch (type) {
            // 需要加开始结束时间的
            case "daterange":
              if (key.endsWith("Time")) {
                const afterTime = key.substring(0, key.lastIndexOf("Time"));
                tempForm[`${afterTime}StartDate`] = ele[0];
                tempForm[`${afterTime}EndDate`] = ele[1];
              } else {
                tempForm[`${key}Start`] = ele[0];
                tempForm[`${key}End`] = ele[1];
              }
              delete tempForm[key];
              break;

            default:
              break;
          }
        }
      }

      // 合并参数
      let params = {
        pageNo: this.inventoryPageNoCode,
        pageSize: this.inventoryPageSize,
        ...tempForm,
        ...this.optionalParams,
        ...loadingParams
      };

      // 请求接口
      this.getTableList(params).then(res => {
        this.setDate(res.data.data.rows);
        this.inventoryTableDatas = res.data.data.rows.map(n => ({
          ...n,
          pkPurmatdetl: n.pkPurmatdetl || generateUUID()
        }));
        this.inventoryTotal = res.data.data.recordsTotal;
        this.inventoryPageNoCode = res.data.data.pageNo;
        // this.inventoryTableData2 = this.selectTableList;

        this.$nextTick(() => {
          this.$refs.inventoryMultipleTable.doLayout();
          if (this.mode === "checkbox") this.$refs.multipleTable2.doLayout();
        });
      });
    },
    inventoryHandleCurrentChange(val) {
      this.inventoryPageNoCode = val;
      this.inventoryGetMcConcBill();
    },
    inventorySearch(searchData) {
      this.inventoryPageNoCode = 1;
      this.inventoryGetMcConcBill();
    },
    inventoryChange(index, key, value) {
      const formDataKeys = Object.keys(this.inventoryForm);
      formDataKeys.map(_ => {
        if (_ !== key) this.inventoryForm[_] = "";
      });
    },
    // 点击行单选
    rowClick(row, event, column) {
      if (this.mode !== "checkbox") return;
      const isExist = this.inventoryTableData2
        .map(n => n.pkPurmatdetl)
        .includes(row.pkPurmatdetl);
      this.handleSelectionChange([row]);

      this.$refs.inventoryMultipleTable.toggleRowSelection(row, !isExist);
    },
    // // 删除
    inventoryDeleteTable(row, index) {
      this.inventoryTableData2 = this.inventoryTableData2.filter(
        item => item.pkPurmatdetl !== row.pkPurmatdetl
      );

      this.$refs.inventoryMultipleTable.toggleRowSelection(row, false);
    },
    // 多选数据
    inventoryConfirm() {
      if (!this.inventoryTableData2.length) {
        return this.$showErrorMessage("未选择数据，请重试");
      }
      this.showDialogVisible = false;
      this.$emit("confirm", this.inventoryTableData2);
      this.resetParams();
    },
    // // 单选数据
    // selectRow(row) {
    //   this.showDialogVisible = false;
    //   this.$emit("confirm", row);
    //   this.resetParams();
    // },
    // 重置表单
    inventoryReset() {
      this.$refs.inventoryForm.resetFields();
    },
    // 单选行数据
    setSelectArr(row) {
      // pkPurmatdetl  每条数据的唯一 id
      // const { pkPurmatdetl } = row;
      // const isExist = this.beforeSelectData.includes(pkPurmatdetl);
      // if (isExist) {
      //   const index = this.beforeSelectData.findIndex(_ => _ === pkPurmatdetl);
      //   // 判断的标志位数组
      //   this.beforeSelectData.splice(index, 1);
      //   // 添加到真正的选中数组
      //   this.inventoryTableData2.splice(index, 1);
      // } else {
      //   this.beforeSelectData.push(pkPurmatdetl);
      //   this.inventoryTableData2.push(row);
      // }
      // this.$refs.inventoryMultipleTable.toggleRowSelection(row, !isExist);
      // this.inventoryTableData2.push(row);
      // this.beforeSelectData.push(row.pkPurmatdetl);
    },
    // 选择行数据
    handleSelectionChange(selection) {
      // 数据去重 并 赋值
      // this.inventoryTableData2 = uniqueByJson(selection, "pkPurmatdetl");
      this.inventoryTableData2 = selection;
    },
    resetParams() {
      this.inventoryPageNoCode = 1;
      this.inventoryPageSize = 10;
      this.inventoryForm = {};
      this.inventoryTableDatas = [];
      this.inventoryTableData2 = [];
      this.$refs.inventoryMultipleTable.clearSelection();
    },
    beforeClose() {
      this.showDialogVisible = false;
      this.resetParams();
    },
    // 时间处理
    setDate(item) {
      // 循环数组
      if (Array.isArray(item)) {
        item.map(Item => {
          this.setDate(Item);
        });
      } else {
        // 循环对象
        for (var key in item) {
          if (item[key]) {
            if (key.indexOf("pdate") != -1) {
              item[key] = item[key].split(" ")[0];
            }
            // 判断类型为 对象类型 循环
            if (item[key] instanceof Object) {
              this.setDate(item[key]);
            }
          }
        }
      }
    },
    getListSmpStockForInventoryPage(data){
        listSmpStockForInventoryPage({
            ...data,
            warehouseId:this.warehouseId,
            pageNo: this.inventoryPageNoCode,
            pageSize: this.inventoryPageSize,
        }).then(res=>{
            this.inventoryTableDatas=res.data.data.rows;
            this.inventoryTableDatas.forEach((item,index)=>{
                // item.
                item.unitPriceWithTax=Number(item.unitPriceWithTax).toFixed(2);
                item.moneyWithTax=Number(item.moneyWithTax).toFixed(2);

                item.actualStockCount=formatNumber(Number(item.actualStockCount),3)
                item.storageCount=formatNumber(Number(item.storageCount),3)
                item.transferLibraryCount=formatNumber(Number(item.transferLibraryCount),3)
                item.unStorageCount=formatNumber(Number(item.unStorageCount),3)
                item.availableStockCount=formatNumber(Number(item.availableStockCount),3)

            })
            this.inventoryTotal=res.data.data.total;
        })
    }
  }
};
</script>

<style lang="scss" scoped>
.inventory {
  display: inline-block;
  & + .inventory {
    margin-left: 10px;
  }
  /deep/ .el-dialog__title {
    display: inline-block;
    height: 20px;
    line-height: 20px !important;
  }
  /deep/ .revenue-code-number {
    .el-dialog__body {
      width: auto;
      height: auto;
      .ccui-form {
        margin-top: 5px;
      }
    }
  }
  /deep/ .revenue-code-number .el-dialog__body .el-dialog__body-bodys {
    .bodys-right {
      padding: 0;
      width: 400px;
    }
  }
  /deep/.el-search .el-searchs {
    float: none !important;
  }
  /deep/.el-searchs-box {
    // width: auto !important;
    margin: 0 auto;
  }
  .container {
    border: 1px solid #f1f1f1;
    padding: 10px 20px;
    .header {
      margin-bottom: 10px;
    }
    .table-footer {
      padding: 10px 0;
    }
    .ccui-statistics-card {
      padding: 0;
    }
  }
  .alert-box {
    margin-bottom: 20px;
  }
  /deep/.el-button--text {
    font-size: 13px;
  }
  /deep/.el-input {
    width: auto;
  }
  .search-btn {
    text-align: center;
    padding: 0 0 20px 0;
  }
  // 搜索条件 启动
  /deep/ .el-form.el-searchs-bottom-form {
    .el-row {
      width: 100%;
    }
    .el-date-editor {
      width: 192px;
      .el-range-input {
        width: 50%;
      }
      .el-range-separator {
        padding: 0 10px 0 5px;
        font-size: 13px;
      }
      .el-range__close-icon,
      .el-range__icon {
        display: none;
      }
    }
  }
  /deep/ .el-dialog__body .el-form .el-form-item:last-child {
    margin-bottom: 16px;
  }
  // 搜索条件 结束
  /deep/ .ccui-multifunctional-table-wrapper .el-table {
    td,
    th.is-leaf {
      border-right: 1px solid #edf2fc;
      border-bottom-color: #f1f1f1;
      border-bottom-width: 1px;
      border-bottom-style: solid;
    }
    // td.is-hidden > *,
    // th.is-hidden > * {
    //   visibility: inherit;
    // }
  }
}
/deep/
  .ccui-multifunctional-table-wrapper
  .el-table__fixed
  .el-table__fixed-body-wrapper
  .el-table__body
  tbody
  .el-table__row
  td {
  border-bottom-width: 1px;
  border-bottom-style: solid;
}
// 解决表格定位滚动条无法拖动
/deep/ .el-table__fixed-header-wrapper {
  th {
    pointer-events: auto;
  }
}
/deep/ .el-table__fixed,
/deep/.el-table__fixed-right {
  pointer-events: none;
  td {
    pointer-events: auto;
  }
}
</style>
